package StudyCode.summary.mycollection;

import java.util.*;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class MultiplicationTableDisplay {
	public static void main(String[] args) {

		int begin = 1, end = 9;

		if (args.length == 2) {
			begin = Integer.parseInt(args[0]);
			end = Integer.parseInt(args[1]);
		}

		SortedMap<Integer, List<Integer>> mt = multTable(begin, end);
		printMultiplicationTable(mt);
		System.out.println();
	}

	public static SortedMap<Integer, List<Integer>> multTable(int begin, int end) {

		if (begin < 0 || end < 0 || begin > end)
			return null;

		SortedMap<Integer, List<Integer>> mt = new TreeMap<>();

		for (int i = begin; i <= end; ++i) {
			List<Integer> li = new ArrayList<>();
			for (int k = begin; k <= end; ++k)
				li.add(i * k);

			mt.put(i, li);
		}

		return mt;
	}

	public static void printMultiplicationTable(
			SortedMap<Integer, List<Integer>> mt) {

		Set<Integer> keys = mt.keySet();
		Integer[] iKeys = keys.toArray(new Integer[0]);
		Integer last = iKeys[iKeys.length - 1];
		int width = Integer.toString(last * last).length() + 1;
		String fmt = "%" + width + "d";

		System.out.printf("%" + width + "s", "");
		for (Integer k : keys)
			System.out.printf(fmt, k);
		System.out.println();

		for (Integer k : keys) {
			System.out.printf(fmt, k);

			List<Integer> li = mt.get(k);
			for (Integer i : li)
				System.out.printf(fmt, i);
			System.out.println();
		}
	}
}

